route.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { isEmpty, pick } from "lodash";
  2. import { NextResponse } from "next/server";
  3. import { WLEDClient } from "wled-client";
  4. import config from "data/config.json";
  5. const action = async ({ client, on }) => {
  6. let wled;
  7. let errors = [];
  8. try {
  9. console.log("connect to", client);
  10. wled = new WLEDClient(client); // setup a connection to the client
  11. await wled.init(); // init the connection
  12. } catch (err) {
  13. errors.push({ error: err.message, type: "connect", client });
  14. }
  15. try {
  16. console.log("set power to", on);
  17. if (on) await wled.turnOn(); // turn off the lights
  18. else await wled.turnOff(); // turn off the lights
  19. } catch (err) {
  20. errors.push({ error: err.message, type: "power", client, on });
  21. }
  22. try {
  23. await wled.refreshState();
  24. } catch (err) {
  25. console.log("state refresh", err.message);
  26. errors.push({ error: err.message, type: "refreshState", client });
  27. }
  28. return { ...pick(wled?.state || {}, ["on"]), errors };
  29. };
  30. export async function GET(req, { params }) {
  31. let id = params?.id;
  32. let promises = [];
  33. try {
  34. if (!id) throw new Error("Invalid power state");
  35. let clients = (config && Object.keys(config)) || [];
  36. if (isEmpty(clients)) throw new Error("No clients found");
  37. for (let client of clients) {
  38. promises.push(action({ client, on: id === "on" || false }));
  39. }
  40. } catch (err) {
  41. return NextResponse.json({ error: err?.message }, { status: 500 });
  42. }
  43. return Promise.allSettled(promises)
  44. .then((results) => {
  45. // console.log("results", results);
  46. return NextResponse.json(results?.map((o) => o?.value));
  47. })
  48. .catch((err) => {
  49. return NextResponse.json({ error: err?.message }, { status: 500 });
  50. });
  51. }